#!/usr/bin/python

import os
import sys
from tempfile import mkstemp

class ClientUpdateError(Exception): pass

class ClientUpdater:
    def __init__(self, exclude_file, update_script, server_name, image_name,  exclude_paths=[]):
        self.exclude_file   = exclude_file
        self.update_script  = update_script
        self.server_name    = server_name
        self.image_name     = image_name
        self.exclude_paths  = exclude_paths
        self.tempname       = None

    def makeExcludeFile(self):
        '''Combine the svn filelist with the systemimager excludes file'''
        (tempfd, self.tempname) = mkstemp()

        orig_exclude_file  = open(self.exclude_file, 'r')
        exclude = orig_exclude_file.read()
        orig_exclude_file.close()

        os.write(tempfd, exclude)
        os.close(tempfd)

        exclude += '\n# excludes added by subcon'
        exclude += '\n%s\n' % self.exclude_file
        new_exclude_file = open(self.exclude_file,'w')
        new_exclude_file.write(exclude)

        self.exclude_paths = [ os.path.join('/',path) for path in self.exclude_paths ]
        self.exclude_paths.sort()
        new_exclude_file.write('\n'.join(self.exclude_paths))
        new_exclude_file.close()

    def revertExcludeFile(self):
        if os.access(self.tempname,os.F_OK):
            os.system('mv %s %s' % (self.tempname, self.exclude_file))

    def buildUpdateCommand(self, dry_run=False):
        command = "%s --no-bootloader --server %s --image %s" % (
            self.update_script,
            self.server_name,
            self.image_name,
            )
        if dry_run:
            command = command + ' --dry-run'
        return command

    def updateClient(self, dry_run=False):
        self.makeExcludeFile()
        command = self.buildUpdateCommand(dry_run)
        rv = os.system(command)
        self.revertExcludeFile()
        if rv != 0: 
            raise ClientUpdateError("update script [%s] failed" % command)
